import Qs from "qs";
import Vue from "vue";
import axios from "axios";
import { DEVAPIADDRESS, PORDAPIADDRESS } from "@/util/config.js";
import { getCookie, isFormData } from '@u/index'
import { MessageBox } from "element-ui";
axios.defaults.baseURL = process.env.NODE_ENV === 'production' ? PORDAPIADDRESS : DEVAPIADDRESS


// let httpCode = {
//   404: "请求资源未找到",
//   500: "内部服务器错误",
//   501: "服务器不支持该请求中使用的方法",
//   502: "网关错误",
//   504: "网关超时"
// };
/** 添加请求拦截器 **/
axios.interceptors.request.use(function (config) {
  let token = getCookie('token')

  axios.defaults.headers.post["Content-Type"] =
    "application/x-www-form-urlencoded";

  if (config.url.indexOf('http') == -1) {
    config.headers.common["Authorization"] = token
  }

  if (config.method === "get") {
    // config.data = { unused: 0 }; // 这个是关键点，加入这行就可以了,解决get,请求添加不上Content-Type
    // 添加时间戳参数，防止浏览器（IE）对get请求的缓存
    // config.params = {
    // 	...config.params,
    // 	 t: new Date().getTime()
    // }

    if (config.params.is_export) config.responseType = 'arraybuffer'

  }


  if (config.method === "post" && !isFormData(config.data)) {
    config.data = Qs.stringify(config.data);
  }

  return config;
})

/** 添加响应拦截器  **/
axios.interceptors.response.use(
  response => {
    if (response.data.code === 200 && (response.data.status == "success" || response.status == 200)) {
      return Promise.resolve(response.data);
    } else if (response.data.code === 401) {
      Vue.prototype.$cookies.remove("token")
      Vue.prototype.$cookies.remove("cookiesAdminUser")
      MessageBox.alert('登录信息失效，请重新登录', '提示', {
        center: true
      }).then(() => {
        location.reload()
      })

      return Promise.resolve(response.data);
    } else {

      let notIndicatedList = [
        "/api/admin/userManagement/company",
        "/api/admin/userManagement/patentee",
        "/api/admin/userManagement/agentLoginList",
        "/api/admin/userManagement/agentWorkload",
        "/api/admin/userManagement/agentList",
        "/api/admin/userManagement/agency",
        "/api/admin/userManagement/inventorList",
        "/api/admin/userManagement/clientList",
        '/api/admin/orderManagement/untreatedOrder',
        "/api/admin/userManagement/inventorLoginList",
        '/api/admin/financialManagement/payRecord/confirmList',
        '/api/admin/orderManagement/countryBureauBefore',
        '/api/admin/orderManagement/countryBureauAfter',
        "/api/admin/financialManagement/drawingCoin/index",
        "/api/admin/financialManagement/drawingCoin/lastMonth",
        "/api/admin/financialManagement/payRecord/onlinePayList",
        "/api/admin/financialManagement/invoiceRecord/index",
        "/api/admin/SettlementManagement/settlement/count",
        "/api/admin/SettlementManagement/settlement/detail",
        '/api/admin/dataStatistics/abnormalDataProcess',
        '/api/admin/dataStatistics/abnormalDataStatistics',
        '/api/admin/userManagement/agencyCase',
        'http://deal-h.whxhhgip.com/getLoginKey',
        'http://deal-h.whxhhgip.com/login',
        'http://deal-a.whxhhgip.com/cPasswordGetKey',
        '/api/admin/videoMake/videoApplicationList',
        '/api/admin/financialManagement/invoiceRecord/uploadInvoicingExcel',
        '/api/admin/SettlementManagement/consumerCoinDetail/detail'
      ]

      if (response.config.url.includes('getDismissFile') ||
          response.config.url.includes('getCpcFile') ||
          // response.config.url.includes('uploadInvoicingExcel') ||
          response.config.url.includes('startInvoicing') ||
          response.config.url.includes('ticketAsyncQuery')
        ) {
        return Promise.resolve(response.data);
      }

      if (notIndicatedList.includes(response.config.url)) return Promise.resolve(response.data);
      MessageBox.alert(response.data.message, "提示", {
        center: true
      });
      return Promise.resolve(response.data);
    }
  },
  error => {
    if (error.response) {
      // 根据请求失败的http状态码去给用户相应的提示
      return Promise.reject(error);
    } else {
      // Toast.fail('请求超时, 请刷新重试')
      return Promise.reject(new Error("请求超时, 请刷新重试"));
    }
  }
)


export const get = (url, data, config = {}) => {

  return axios({
    method: "get",
    url,
    params: { ...data },
    ...config
  })
    .then(response => {
      return Promise.resolve(response);
    })
    .catch(error => {
      return Promise.reject(error);
    });
};

export const post = (url, data, config = {}) => {
  return axios({
    method: "post",
    url,
    data,
    ...config
  })
    .then(response => {
      return Promise.resolve(response);
    })
    .catch(error => {
      return Promise.reject(error);
    });
};

export const put = (url, data, config = {}) => {
  return axios({
    method: "put",
    url,
    data,
    ...config
  })
    .then(response => {
      return Promise.resolve(response);
    })
    .catch(error => {
      return Promise.reject(error);
    });
};
export const del = (url, data, config = {}) => {
  return axios({
    method: "delete",
    url,
    data: { ...data },
    ...config
  })
    .then(response => {
      return Promise.resolve(response);
    })
    .catch(error => {
      return Promise.reject(error);
    });

};
